package com.xlh.job;

import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import com.xlh.dao.courseTest.CourseQuestionRepositoryDetailsMapper;
import com.xlh.dao.courseTest.CourseQuestionRepositoryDetailsMapperExt;
import com.xlh.dao.courseTest.CourseQuestionRepositoryMapper;
import com.xlh.enums.LocalResourcesEnum;
import com.xlh.pojo.courseTest.CourseQuestionRepository;
import com.xlh.pojo.courseTest.CourseQuestionRepositoryDetails;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * 题库定时任务，清理从表脏数据以及io脏数据文件
 *
 * @author zhr 2019/3/15
 */
@Component
public class RepositoryTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryTask.class);

    @Autowired
    private CourseQuestionRepositoryMapper repositoryMapper;
    @Autowired
    private CourseQuestionRepositoryDetailsMapper detailsMapper;
    @Autowired
    private CourseQuestionRepositoryDetailsMapperExt detailsMapperExt;

    /**
     * 每天凌晨1点执行题库定时清理任务
     */
    @Scheduled(cron = "0 0 1 * * *")
    public void repositoryClean() {
        LOGGER.info("开始执行题库定时清理任务");

        // 清理服务器静态文件
//        cleanFiles();

        // 清理从表中的脏数据
        cleanRepositoryDetails();

        LOGGER.info("执行题库定时清理任务完毕");
    }

    private void cleanRepositoryDetails() {
        detailsMapperExt.clean();
    }

    private void cleanFiles() {
        File[] courseDirs = FileUtil.ls(LocalResourcesEnum.COURSE.getLocalUploadPath());
        // 存放在服务器上的所有io文件
        List<String> allRepositoryFiles = Lists.newArrayList();
        for (File file : courseDirs) {
            String absoluteDir = StringUtils.join(file.getAbsolutePath(), "/repository/").replace("\\", "/");
            List<String> files = FileUtil.listFileNames(absoluteDir);
            for (String fileName : files) {
                allRepositoryFiles.add(StringUtils.join(absoluteDir, fileName));
            }
        }

        List<CourseQuestionRepository> repositoryList = repositoryMapper.selectByExample(null);
        List<CourseQuestionRepositoryDetails> detailsList = detailsMapper.selectByExample(null);

        // 记录在数据库中的全部文件
        List<String> allExistRepositoryFiles = Lists.newArrayList();
        for (CourseQuestionRepository repository : repositoryList) {
            allExistRepositoryFiles.add(joinAbsolutePath(repository.getPath(), repository.getContent()).replace("//", "/"));
        }
        for (CourseQuestionRepositoryDetails details : detailsList) {
            allExistRepositoryFiles.add(joinAbsolutePath(details.getPath(), details.getContent()).replace("//", "/"));
        }

        List<String> deletedRepositoryFiles = ListUtils.removeAll(allRepositoryFiles, allExistRepositoryFiles);
        for (String fileName : deletedRepositoryFiles) {
            FileUtil.del(fileName);
        }
    }

    private String joinAbsolutePath(String fileDir, String fileName) {
        return StringUtils.join(fileDir, fileDir.endsWith("/") ? "" : "/", fileName);
    }
}
